<template>
  <div class="wxuser">
    <el-row>
      <el-col :offset="8" :span="8">
        <div class="wxuser-logo">
          <img src="../../../public/images/avatar.png" alt="" />
        </div>
        <el-steps :active="step" align-center finish-status="success">
          <el-step title="选择账号"></el-step>
          <el-step title="选择应用"></el-step>
          <el-step title="确认进入"></el-step>
        </el-steps>
        <div class="wxuser-main">
          <transition name="el-zoom-in-center">
            <div class="wxuser-card" v-show="show1">
              <el-card class="box-card" shadow="always">
                <div class="wxuser-title">
                  <h2 class="fs-title">选择你使用的账号</h2>
                  <h3 class="fs-subtitle">这是第一步</h3>
                </div>
                <div class="wxuser-content">
                  <el-scrollbar style="height:100%">
                    <div class="main" v-if="account.length">
                      <template v-for="(acc, key) in account">
                        <div
                          @click="select1(key)"
                          class="item"
                          :class="{ active: key === index1 }"
                          :key="key"
                        >
                          <i class="el-icon-user-solid mr5"></i>
                          {{ acc.username }}
                          <p class="ml5 email">{{ acc.email }}</p>
                        </div>
                      </template>
                    </div>
                    <div v-else class="empty">
                      <i class="el-icon-receiving"></i>
                      <p class="tip">
                        微信账号无此平台账号，点击右下角<strong
                          >‘注册新的账号’</strong
                        >
                      </p>
                    </div>
                  </el-scrollbar>
                  <div class="flx mt20">
                    <el-button :disabled="btn1" @click="go(2)" type="info" round
                      >下一步</el-button
                    >
                    <div class="link">
                      <router-link
                        :to="{
                          name: 'regist',
                          params: { openid, access_token }
                        }"
                      >
                        <el-link icon="el-icon-document-add" type="primary"
                          >注册新的账号</el-link
                        >
                      </router-link>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </transition>
          <transition name="el-zoom-in-center">
            <div class="wxuser-card" v-show="show2">
              <el-card class="box-card" shadow="always">
                <div class="wxuser-title">
                  <h2 class="fs-title">选择当前环境下的应用</h2>
                  <h3 class="fs-subtitle">这是第二步</h3>
                </div>
                <div class="wxuser-content">
                  <el-scrollbar style="height:100%">
                    <div class="main" v-if="application.length">
                      <template v-for="(app, key) in application">
                        <div
                          @click="select2(key)"
                          class="item"
                          :class="{ active: key === index2 }"
                          :key="key"
                        >
                          <i class="el-icon-s-help mr5"></i>
                          {{ app.name }} &nbsp; (&nbsp;
                          <strong>{{ app.typedata | dataType }}</strong>
                          &nbsp;)
                        </div>
                      </template>
                    </div>
                    <div v-else class="empty">
                      <i class="el-icon-receiving"></i>
                      <p class="tip">
                        此平台账号无关联应用，点击右下角<strong
                          >‘关联新应用’</strong
                        >
                      </p>
                    </div>
                  </el-scrollbar>
                  <div class="flx mt20">
                    <el-button @click="back(1)" type="success" round
                      >上一步</el-button
                    >
                    <el-button type="info" @click="go(3)" round
                      >下一步</el-button
                    >
                    <div class="link">
                      <router-link :to="{ path: 'registered' }">
                        <el-link icon="el-icon-document-add" type="primary"
                          >注册(绑定)新的应用</el-link
                        >
                      </router-link>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </transition>
          <transition name="el-zoom-in-center">
            <div class="wxuser-card" v-show="show3">
              <el-card class="box-card" shadow="always">
                <div class="wxuser-title">
                  <h2 class="fs-title">进入应用</h2>
                  <h3 class="fs-subtitle">最后一步</h3>
                </div>
                <div class="content">
                  <div class="main">
                    <h3 class="fs-subtitle">您选择的账号</h3>
                    <div class="user flx">
                      <strong>"{{ currentAccount.username }}"</strong>
                    </div>
                    <h3 class="fs-subtitle">您选择的应用</h3>
                    <div class="app flx">
                      <strong>"{{ currentApplication.name }}"</strong>
                    </div>
                  </div>
                  <div class="flx mt20">
                    <el-button @click="back(2)" type="success" round
                      >上一步</el-button
                    >
                    <el-button @click="start" :disabled="btn2" type="info" round
                      >进入</el-button
                    >
                  </div>
                </div>
              </el-card>
            </div>
          </transition>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { qrcodeWxUsers, getWxapp } from "@/api/wx";
import { mapActions, mapGetters } from "vuex";
export default {
  name: "wxuser",
  data() {
    return {
      redirect: null,
      otherQuery: null,
      show1: true,
      show2: false,
      show3: false,
      index1: null,
      index2: null,
      step: 0,
      account: [],
      openid: "",
      access_token: "",
      application: []
    };
  },
  computed: {
    ...mapGetters(["wechatAccount"]),
    currentAccount() {
      return this.account[this.index1]
        ? this.account[this.index1]
        : { username: null };
    },
    // ↓ 选择账号下一页按键开关 ↓
    btn1() {
      return this.index1 === null ? true : false;
    },
    currentApplication() {
      return this.application[this.index2]
        ? this.application[this.index2]
        : { name: null };
    },
    btn2() {
      return this.currentAccount.username && this.currentApplication.name
        ? false
        : true;
    }
  },
  created() {
    if (this.wechatAccount) {
      let accounts = this.wechatAccount;
      this.desParams(JSON.parse(accounts));
    } else {
      this.getUsers();
    }
  },
  methods: {
    ...mapActions({
      wechatLogin: "user/wechatLogin",
      setUserApp: "user/setUserApp",
      setWechatAccount: "user/setWechatAccount"
    }),
    // ↓ 解构路由其他参数 ↓
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    // ↓ 获取扫码用户下所拥有的账户 ↓
    async getUsers() {
      if (this.otherQuery && this.otherQuery.code) {
        let response = await qrcodeWxUsers(this.otherQuery.code);
        if (response.data && response.data.accountList) {
          let res = response.data.accountList;
          this.setWechatAccount(JSON.stringify(res));
          this.desParams(res);
        }
      } else {
        // ↓ url地址栏没有需要的 code 返回登录页  ↓
        this.$notify({
          title: "失败",
          message: "扫码code无效,返回登录页!",
          type: "error"
        });
        // this.$router.back(-1);
      }
    },
    desParams(res) {
      Object.keys(res).forEach(item => {
        if (item - 0 >= 0) {
          this.account.push(res[item]);
        }
      });
      this.openid = res.openid;
      this.access_token = res.access_token;
    },
    // ↓ 微信扫码登录后选择帐号登录 ↓
    async wxlogin() {
      let data = {
        email: this.currentAccount.email,
        openid: this.openid,
        access_token: this.access_token,
        password: "any"
      };
      if (!(await this.wechatLogin(data))) {
        // ↓ 微信扫码登录后选择帐号登录 ↓
        let res = await getWxapp(this.currentAccount.username);
        this.application = res.data;
      }
    },
    go(num) {
      switch (num) {
        case 2:
          this.step = 1;
          this.show1 = false;
          this.show2 = true;
          break;
        case 3:
          this.step = 2;
          this.show2 = false;
          this.show3 = true;
          break;
      }
    },
    back(num) {
      switch (num) {
        case 1:
          this.step = 0;
          this.show1 = true;
          this.show2 = false;
          break;
        case 2:
          this.step = 1;
          this.show2 = true;
          this.show3 = false;
          break;
      }
    },
    select1(num) {
      if (this.index1 !== num) {
        this.index1 = num;
        this.index2 = 0;
        this.wxlogin();
      }
    },
    select2(num) {
      if (this.index2 !== num) {
        this.index2 = num;
      }
    },
    start() {
      this.$http
        .get("applet/setapplet/" + this.currentApplication.id)
        .then(response => {
          if (response.code === 10000) {
            this.setUserApp({
              name: this.currentApplication.name,
              appid: response.data.appid
            });
            this.$router.push({
              path: this.redirect || "/dashboard",
              query: this.otherQuery
            });
          }
        });
    }
  },
  watch: {
    // ↓ 监听地址栏 解构出 重定向 参数 和 其他参数 ↓
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  filters: {
    dataType(type) {
      let resType = null;
      switch (type) {
        case "serv_account":
          resType = "服务号";
          break;
        case "miniapp":
          resType = "小程序";
          break;
        case "sub_account":
          resType = "订阅号";
          break;
        case "work_account":
          resType = "企业微信";
          break;
        case "web":
          resType = "网站应用";
          break;
        case "app":
          resType = "移动应用";
          break;
        default:
          resType = "未知类型";
          break;
      }
      return resType;
    }
  }
};
</script>
<style lang="scss" scoped>
.wxuser {
  height: 100%;
  background: url("../../../public/images/gs.png");
  background: linear-gradient(rgba(196, 102, 0, 0.2), rgba(155, 89, 182, 0.2)),
    url("../../../public/images/gs.png");
  &-logo {
    text-align: center;
  }
  &-title {
    text-align: center;
  }
  &-main {
    position: relative;
  }
  &-content {
    .main {
      max-height: 300px;
      min-height: 150px;
      .item {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        font-size: 16px;
        padding: 15px;
        border: 1px solid #eee;
        border-radius: 3px;
        color: #757575;
        transition: all 0.3s ease-in;
        &:hover {
          background-color: #3f51b5;
          color: white;
        }
        .email {
          margin: 0;
          margin-left: 10px;
          color: #bdbdbd;
          font-size: 12px;
        }
      }
      .active {
        background-color: #3f51b5;
        color: white;
      }
      .user,
      .app {
        font-size: 18px;
        margin-bottom: 20px;
      }
    }
    .empty {
      font-size: 60px;
      height: 200px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #bdbdbd;
      .tip {
        font-size: 12px;
      }
    }
    .link {
      position: absolute;
      right: 10px;
    }
  }

  &-card {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
  }
}
/*headings*/
.fs-title {
  font-size: 15px;
  text-transform: uppercase;
  color: #2c3e50;
  margin-bottom: 10px;
}
.fs-subtitle {
  font-weight: normal;
  font-size: 13px;
  color: #666;
  margin-bottom: 10px;
}
.flx {
  display: flex;
  justify-content: center;
  align-items: center;
}
.mt20 {
  margin-top: 20px;
}
.mr5 {
  margin-right: 5px;
}
.ml5 {
  margin-left: 5px;
}
</style>
